package handler

import (
	"github.com/gin-gonic/gin"
	jwt "github.com/golangblogs/gojwt"
	"net/http"
	"zk3.12/api/request"
	"zk3.12/glodal"
	"zk3.12/internal/model"
)

func UserUpAndAdd(c *gin.Context) {
	var req request.UserUpAndAdd
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	err = glodal.DB.Where("name = ?", req.Name).First(&user).Error
	if user.ID == 0 {
		user = model.User{
			Name:     req.Name,
			Password: req.Password,
		}
		glodal.DB.Create(&user)
		if user.ID == 0 {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "用户注册失败",
				"data": nil,
			})
			return
		}
	} else {
		if req.Password != user.Password {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "密码错误",
				"data": nil,
			})
			return
		}
	}
	token, _ := jwt.NewJWT("2210y").CreateToken(jwt.CustomClaims{
		ID: user.ID,
	})
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": token,
	})
}
